package com;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmh.service.http.utils.HttpAPIService;
import com.zmh.service.http.utils.HttpResult;


/** 
 * @author: zhoumh
 * @version: 创建时间：2018年12月4日 上午8:55:45 
 * @Description: 
 * 1、登录
 * 2、请求详细页
 * 3、保存
*/ 
@Service
@EnableScheduling
public class WorkPunchHttp {
	private static Logger logger = LoggerFactory.getLogger(WorkPunchHttp.class);
//	private static String baseUrl = "http://192.168.10.24:8100/";
	@Autowired
	private HttpAPIService httpAPIService;
	@Autowired
	private WorkPunchMapper workPunchMapper;
	
	@Scheduled(cron = "0 0,10,20,30 8,17 * * *")
	public void workPunch() throws Exception {
		logger.info("开始获取考勤记录");
		login();
		getPunch();
		logger.info("本次考勤记录获取结束");
	}
	
	public void login() throws Exception {
//		{"user":{"userName":"1084","password":"9f36407ead0629fc166f14dde7970f68"},"loginURL":"http://192.168.10.24:8100/login.html"}
		JSONObject user = new JSONObject();
		user.put("userName", "1084");
		user.put("password", "9f36407ead0629fc166f14dde7970f68");
		JSONObject login = new JSONObject();
		login.put("loginURL", "http://192.168.10.24:8100/login.html");
		login.put("user", user);
		// 登录
		HttpResult result = httpAPIService.doPostJson("http://192.168.10.24:8100/login.whtml",login.toJSONString());
		if (result.getCode()==200&&result.getBody().indexOf("登陆成功！")>-1) {
			logger.info("workpunch登录成功！");
		}
	}
	//查询当前天的工作日志情况
	public void getPunch() throws Exception {
//		cardQueryParameter.begin=2018-11-25T00%3A00%3A00%2B08%3A00&cardQueryParameter.end=2018-12-04T00%3A00%3A00%2B08%3A00&start=0&count=25
		Map<String, Object> post = new HashMap<String, Object>();
		post.put("cardQueryParameter.begin", subHour(getDate()+" 00:00:00", 24));
		post.put("cardQueryParameter.end", getDate()+" 23:59:59");
		post.put("start", 0);
		post.put("count", 25);
		HttpResult result = httpAPIService.doPost("http://192.168.10.24:8100/selfProcess/queryCurrentUserCardInfo.whtml",post);
		JSONObject html = JSONObject.parseObject(result.getBody());
		JSONArray items = html.getJSONArray("items");
		for (int i = 0; i < items.size(); i++) {
			JSONObject item = items.getJSONObject(i);
			logger.info(item.toJSONString());
			//取出每一天的考勤记录
			String date = item.getString("date");
			JSONArray periodCardInfoList = item.getJSONArray("periodCardInfoList");
			JSONObject am = periodCardInfoList.getJSONObject(0); //上午
			String beginCardTpmAm = am.getJSONObject("beginCardTpm").getString("time");
			String endCardTpmAm = am.getJSONObject("endCardTpm").getString("time");
			if (!StringUtils.isEmpty(beginCardTpmAm)) { //打卡时间不为空
				saveCardTp(beginCardTpmAm, endCardTpmAm, "am", date); //记录上午打卡
			}
			JSONObject pm = periodCardInfoList.getJSONObject(1); //下午
			String beginCardTpmPm = pm.getJSONObject("beginCardTpm").getString("time");
			String endCardTpmPm = pm.getJSONObject("endCardTpm").getString("time");
			if (!StringUtils.isEmpty(endCardTpmPm)) { //打卡时间不为空
				saveCardTp(beginCardTpmPm, endCardTpmPm, "pm", date);  //记录下午打卡
			}
		}
	}
	
	/**
	 * 保存考勤记录
	 * 1、判断当天考勤记录是否已存在
	 * 2、如果不存在考勤记录时才执行插入
	 */
	private void saveCardTp(String begin,String end,String type,String date) {
		int result = workPunchMapper.getCount(date, type);
		if (result==0) {
			workPunchMapper.insert(begin, end, type, date); //记录上午打卡
		}
	}
	/**
	 * 获得服务器当前日期，以格式为：yyyy-MM-dd的日期字符串形式返回
	 * @author zhoumh
	 * @version 创建时间：2017年6月27日 下午4:37:11
	 * @return yyyy-MM-dd
	 */
	public static String getDate() {
		final String FORMAT = "yyyy-MM-dd"; //日期转换格式
		try {
			return new SimpleDateFormat(FORMAT).format(System.currentTimeMillis());
		} catch (Exception e) {
			logger.debug("DateUtil.getDate():" + e.getMessage());
			return "";
		}
	}
	
	/**
	 * 给传入的时间减少小时
	 * @param dt 时间基数 2017-06-27 14:29:10
	 * @param h 要减少的小时数 2
	 * @return: String 增加小时之后的时间 2017-06-27 16:29:10
	 * @author: zhoumh
	 * @version: 创建时间：2017年11月15日 上午8:54:31 
	 * @Description:
	 */
	public static String subHour(String dt,int h){
		//将小时数转换成毫秒
	    long ms = h * 60 * 60 * 1000;
	    //日期格式转换
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 将传入时间转换成毫秒格式
		long ts = 0;
		try {
			ts = formatter.parse(dt).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			logger.error("计算错误");
		}
		return formatter.format(ts - ms);
	}
}
